package cn.cdeden.knowledge.controller.team;

import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.core.utils.MessageUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.Team;
import cn.cdeden.knowledge.domain.TeamFilesTree;
import cn.cdeden.knowledge.domain.dto.*;

import cn.cdeden.knowledge.domain.enums.MessageTypeEnums;
import cn.cdeden.knowledge.domain.enums.SysParametersConfigEnums;
import cn.cdeden.knowledge.enums.*;
import cn.cdeden.knowledge.service.*;
import cn.cdeden.knowledge.utils.FileStorageUtils;
import cn.cdeden.knowledge.utils.FilesLabelUtils;
import cn.cdeden.knowledge.utils.SysConfigUtils;
import cn.cdeden.system.api.model.LoginUser;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Chen
 * @date 2022-09-16
 **/
@Controller
@Slf4j
//@Api(tags = "团队文档树管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/teamFilesTree")
public class TeamFilesTreeController {

    private final TeamFilesTreeService teamFilesTreeService;

    private final TeamRelevanceRoleService teamRelevanceRoleService;

    private final TeamService teamService;

    private final SysDocLogService sysDocLogService;

    private final FilesAttentionService filesAttentionService;

    private final SysMessageService messageService;

    private final TeamMemberService teamMemberService;

//    @Autowired
//    private RabbitMessageSender rabbitMessageSender;
    @Autowired
    private EnterpriseFilesTreeService enterpriseFilesTreeService;

//    @Log("查询团队文档树")
//    @ApiOperation("查询团队文档树")
    @GetMapping(value = "/query")
    @ResponseBody
    public R query(TeamFilesTreeQueryParam query) {
        return R.ok(teamFilesTreeService.queryAll(query));
    }


//    @Log("团队高级搜索")
//    @ApiOperation("团队高级搜索")
    @GetMapping(value = "/teamAdvancedSearch")
    @ResponseBody
    public R teamAdvancedSearch(TeamQueryParam query, Pageable pageable) {
        return R.ok(teamService.queryByPerm(query, pageable));
    }

//    @Log("查询团队文档树(分页)")
//    @ApiOperation("查询团队文档树(分页)")
    @GetMapping(value = "/queryPaging")
    @ResponseBody
    public R queryPaging(TeamFilesTreeQueryParam query, Pageable pageable) {
        if (null == query.getRealName()) {
            return R.ok();
        }
        TableDataInfo<TeamFilesTreeDto> info = teamFilesTreeService.queryAll(query, pageable);
        return R.ok(info);
    }

//    @Log("团队文档:查询团队树(操作日志查询)")
//    @ApiOperation("团队文档:查询团队树(操作日志查询)")
    @GetMapping(value = "/selectAll")
    public R<List<TeamFilesTreeDto>> selectAll(String parentId) {
        return R.ok(teamFilesTreeService.selectAll(parentId));
    }

//    @Log("团队文档:查询团队树(文件夹)")
//    @ApiOperation("团队文档:查询团队树(文件夹)")
    @GetMapping(value = "/selectTree")
    public R selectTree(TeamFilesTreeQueryParam query) {
        //验证是否是团队成员
        if (!teamMemberService.checkPermission(query.getTeamId(), LoginHelper.getLoginUser(), TeamParamEnum.CHECK.getParam())) {
            return R.fail(ResultEnum.PERM_ERROR.getNum(), "无查看权限，请联系管理员");
        }
        TeamFilesTreeDto treeVos = teamFilesTreeService.selectTree(query);
        return R.ok(treeVos);
    }

//    @Log("团队文档:查询个人树(分页)")
//    @ApiOperation("团队文档:查询团队树(分页)")
    @GetMapping(value = "/selectTreePage")
    public R selectTreePage(TeamFilesTreeQueryParam query, Pageable pageable) {
        //验证是否是团队成员
        if (!teamMemberService.checkPermission(query.getTeamId(), LoginHelper.getLoginUser(), TeamParamEnum.CHECK.getParam())) {
            return R.fail(ResultEnum.PERM_ERROR.getNum(), "无查看权限，请联系管理员");
        }
        TableDataInfo<TeamFilesTreeDto> info = teamFilesTreeService.selectTreePage(query, pageable);
        return R.ok(info);
    }

//    @Log("新增团队文档文件夹")
//    @ApiOperation("新增团队文档文件夹")
    @PostMapping(value = "/addFolder")
    @ResponseBody
    public R create(@RequestBody TeamFilesTreeInsertParam teamFilesTreeInsertParam) {
        //团队角色权限
        if (!teamRelevanceRoleService.checkPermission(teamFilesTreeInsertParam.getParentId(), teamFilesTreeInsertParam.getTeamId(), LoginHelper.getLoginUser(), TeamParamEnum.ADD.getParam())) {
            return R.fail(ResultEnum.PERM_ERROR.getNum(), "无新建权限，请联系管理员");
        }
        TeamFilesTreeDto teamFilesTreeDto = teamFilesTreeService.createFolder(teamFilesTreeInsertParam, String.valueOf(LoginHelper.getLoginUser().getUserId()));
        if (teamFilesTreeDto.getDuplicate()) {
            return R.fail("已有重名的文件夹");
        }
        return R.ok(teamFilesTreeDto);
    }

//    @Log("团队文档文件夹重命名")
//    @ApiOperation("团队文档文件夹重命名")
    @PostMapping(value = "/rename")
    @ResponseBody
    public R rename(@Valid @RequestBody TeamFilesTreeRenameParam teamFilesTreeRenameParam) {
        Long id = teamFilesTreeRenameParam.getId();
        String realName = teamFilesTreeRenameParam.getRealName();
        TeamFilesTree teamFilesTree = teamFilesTreeService.getById(id);

        if (!teamRelevanceRoleService.checkPermission(String.valueOf(id), teamFilesTree.getTeamId(), LoginHelper.getLoginUser(), TeamParamEnum.UPDATE.getParam())) {
            return R.fail(ResultEnum.PERM_ERROR.getNum(), "无修改权限，请联系管理员");
        }
//        if (teamFilesTreeService.nameRechecking(realName, teamFilesTree.getParentId(), teamFilesTree.getSuffix()) != null) {
//            return R.ok("201", "该目录下有文件重名，是否覆盖？");
//        }
        TeamFilesTreeDto resources = new TeamFilesTreeDto();
        resources.setId(id);
        resources.setRealName(realName);

        if (null != teamFilesTreeRenameParam.getRealName()) {
            if (!teamFilesTreeService.rename(resources))
                return R.fail(ResultEnum.PERM_ERROR.getNum(), "文件名已存在");
        }

        List<String> attentionPeople = filesAttentionService.getAttentionPeople(String.valueOf(id), "1");
        for (String attentionPerson : attentionPeople) {
            //创建消息
//            MessageTypeChildEnums messageTypeChildEnums = null;
//            switch (teamFilesTree.getType()) {
//                case "file":
//                    messageTypeChildEnums = MessageTypeChildEnums.TEAM_FILE;
//                    break;
//                case "folder":
//                    messageTypeChildEnums = MessageTypeChildEnums.TEAM_FOLDER;
//                    break;
//                case "richText":
//                    messageTypeChildEnums = MessageTypeChildEnums.TEAM_RICHTEXT;
//                    break;
//            }
            LoginUser user = LoginHelper.getLoginUser();
//            messageUtils.create(MessageFileTypeEnums.FILE, messageTypeChildEnums.getLibraryType(), String.valueOf(teamFilesTree.getId()), String.valueOf(user.getUserId()), attentionPerson, "您关注的: “" + teamFilesTree.getRealName() + "”  “" + teamFilesTree.getRealName() + "”重命名为：" + realName + "。 操作人：" + user.getNickname(), messageTypeChildEnums.getType(), String.valueOf(teamFilesTree.getTeamId()));
            //创建消息
            SysMessageDto sysMessageDto = new SysMessageDto();
            sysMessageDto.setContent("您关注的: “" + teamFilesTree.getRealName() + "”  “" + teamFilesTree.getRealName() + "”重命名为：" + realName + "。 操作人：" + user.getNickname());
            sysMessageDto.setOperator(LoginHelper.getUserId().toString());
            sysMessageDto.setNodeId(String.valueOf(teamFilesTree.getId()));
            sysMessageDto.setMessageType("0");
            sysMessageDto.setType(MessageTypeEnums.ADD.getCode());
            sysMessageDto.setFileType(MessageFileTypeEnums.TEAM.getCode());
            sysMessageDto.setRecipient(attentionPerson);
            sysMessageDto.setTeamId(String.valueOf(teamFilesTree.getTeamId()));
            messageService.addMessage(sysMessageDto);
        }

        //创建日志
        sysDocLogService.createLog(String.valueOf(id), null, TreeEnum.TEAM, OperationEnum.UPDATE.getOperation(OperationEnum.OperationTypeEnum.FOLDER), teamFilesTree.getRealName(), teamFilesTree.getPath(), null);

        return R.ok(teamFilesTreeService.updateById(resources));
    }

//    @Log("修改团队文档描述")
//    @ApiOperation("修改团队文档描述")
    @PostMapping(value = "/updateRemarks")
    @ResponseBody
    public R updateRemarks(@RequestBody TeamFilesTreeRenameParam teamFilesTreeRenameParam) {
        Long id = teamFilesTreeRenameParam.getId();
        String remarks = teamFilesTreeRenameParam.getRemarks();
        TeamFilesTree teamFilesTree = teamFilesTreeService.getById(id);

        if (!teamRelevanceRoleService.checkPermission(String.valueOf(id), teamFilesTree.getTeamId(), LoginHelper.getLoginUser(), TeamParamEnum.UPDATE.getParam())) {
            return R.fail(ResultEnum.PERM_ERROR.getNum(), "无修改权限，请联系管理员");
        }
        TeamFilesTreeDto resources = new TeamFilesTreeDto();
        resources.setId(id);
        resources.setRemarks(remarks);

        //创建日志
        sysDocLogService.createLog(String.valueOf(id), null, TreeEnum.TEAM, OperationEnum.UPDATE.getOperation(OperationEnum.OperationTypeEnum.FOLDER), teamFilesTree.getRealName(), teamFilesTree.getPath(), null);

        return R.ok(teamFilesTreeService.updateById(resources));
    }

//    @Log("删除团队文档文件")
//    @ApiOperation("删除团队文件")
    @GetMapping(value = "/delete")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "ids", value = "删除ID数组", dataType = "List", required = false),
//    })
    @Transactional
    public R delete(@RequestParam List<Long> ids) {
        R r = null;
        LoginUser user = LoginHelper.getLoginUser();
        for (Long id : ids) {
            TeamFilesTree teamFilesTree = teamFilesTreeService.getById(id);

            FilesLabelUtils filesLabelUtils = new FilesLabelUtils();
            filesLabelUtils.deleteRecordTeam(String.valueOf(id), teamFilesTree.getTeamId());

            if (teamFilesTree.getCreateId().equals(String.valueOf(user.getUserId()))) {
                TeamFilesTreeDto teamFilesTreeDto = new TeamFilesTreeDto();
                teamFilesTreeDto.setId(id);
                teamFilesTreeDto.setDeleteId(String.valueOf(user.getUserId()));
                teamFilesTreeDto.setDeleteBy(String.valueOf(user.getNickname()));
                teamFilesTreeDto.setDeleteTime(new Date());
                r = R.ok(teamFilesTreeService.updateById(teamFilesTreeDto));

                //创建日志
                sysDocLogService.createLog(String.valueOf(id), null, TreeEnum.TEAM, OperationEnum.DELETE.judgmentType(teamFilesTree.getType()), teamFilesTree.getRealName(), teamFilesTree.getPath(), null);
            } else {
                return cn.cdeden.common.core.domain.R.fail(ResultEnum.PERM_ERROR.getNum(), "无删除权限，请联系管理员");
            }
        }
        return r;
    }


//    @Log("团队树复制")
//    @ApiOperation("团队树复制")
    @PostMapping(value = "/treeCopy")
    @ResponseBody
//    @ApiImplicitParams({
////            @ApiImplicitParam(name = "parentId",value = "父类ID",dataType = "String")
//    })
    @Transactional
    public R treeCopy(@RequestBody RecoverFileChooseAPath chooseAPath) {
        List<String> ids = chooseAPath.getIds();
        for (String id : ids) {
            TeamFilesTree teamFilesTree = teamFilesTreeService.getById(id);
            if (!teamRelevanceRoleService.checkPermission(id, teamFilesTree.getTeamId(), LoginHelper.getLoginUser(), TeamParamEnum.COPY.getParam())) {
                return R.fail(ResultEnum.PERM_ERROR.getNum(), "无复制权限，请联系管理员");
            }
        }

        if (chooseAPath != null
                && CollectionUtils.isEmpty(ids)
                && StringUtils.isEmpty(chooseAPath.getParentId())
                && chooseAPath.getIds().size() >= 1
        ) {
            throw new RuntimeException("缺少数据");
        }
        return teamFilesTreeService.fileTreeCopy(chooseAPath);
    }


//    @Log("团队树移动")
//    @ApiOperation("团队树移动")
    @PostMapping(value = "/fileTreeMove")
    @ResponseBody
//    @ApiImplicitParams({
////            @ApiImplicitParam(name = "parentId",value = "父类ID",dataType = "String")
//    })
    @Transactional
    public R fileTreeMove(@RequestBody RecoverFileChooseAPath chooseAPath) {
        List<String> ids = chooseAPath.getIds();
        for (String id : ids) {
            TeamFilesTree teamFilesTree = teamFilesTreeService.getById(id);
            if (!teamRelevanceRoleService.checkPermission(id, teamFilesTree.getTeamId(), LoginHelper.getLoginUser(), TeamParamEnum.MOVE.getParam())) {
                return R.fail(ResultEnum.PERM_ERROR.getNum(), "无移动权限，请联系管理员");
            }
        }
        if (
                chooseAPath != null
                        && CollectionUtils.isEmpty(ids)
                        && StringUtils.isEmpty(chooseAPath.getParentId())
                        && chooseAPath.getIds().size() >= 1
        ) {
            throw new RuntimeException("缺少数据");
        }
        return teamFilesTreeService.fileTreeMove(chooseAPath);
    }

//    @Log("修改生命周期")
//    @ApiOperation("修改生命周期")
    @GetMapping(value = "/fileEnhance")
    @ResponseBody
    public R fileEnhance(TeamFilesTreeDto teamFilesTreeDto) {
        TeamFilesTree teamFilesTree = teamFilesTreeService.getById(teamFilesTreeDto.getId());
        Team team = teamService.getById(teamFilesTree.getTeamId());
        Long id = LoginHelper.getLoginUser().getUserId();
        if (!team.getOwner().equals(id.toString()) && !teamFilesTree.getCreateId().equals(id.toString())) {
            return R.fail(ResultEnum.PERM_ERROR.getNum(), "无修改权限，请联系管理员");
        }
        return R.ok(teamFilesTreeService.updateById(teamFilesTreeDto));
    }

//    @Log("团队文档加入培训资源")
//    @ApiOperation("团队文档加入培训资源")
//    @GetMapping(value = "/joinTMS")
//    @ResponseBody
//    public R joinTMS(String id) {
//        TeamFilesTree teamFilesTree = teamFilesTreeService.getById(id);
//        FileUserDto user = FileUserUtils.getUser();
//
//        //判断是否有权限
//        if (!teamRelevanceRoleService.checkPermission(id, teamFilesTree.getTeamId(), user, TeamParamEnum.JURISDICTION.getParam())) {
//            throw new BadRequestException("无操作权限，请联系管理员");
////            return R.fail()(ResultEnum.PERM_ERROR.getNum(), "无操作权限，请联系管理员");
//        }
//
//        //判断是否开启TMS继承
//        SysParametersConfigDto trainEnable = sysConfigUtils.getByConfigCodeAfter("train_enable", SysParametersConfigEnums.SYS_EXTERNAL_CONFIG);
//        if (!trainEnable.getConfigValue().equals("true")) {
//            throw new BadRequestException("未开启TMS集成");
////            return R.fail()(ResultEnum.PERM_ERROR.getNum(), "未开启TMS集成");
//        }
//
//        //判断在TMS中是否存在相同的问题，如果有相同的文件提示修改名称
//        SysParametersConfigDto trainUrl = sysConfigUtils.getByConfigCodeAfter("train_url", SysParametersConfigEnums.SYS_EXTERNAL_CONFIG);
//        RestTemplate restTemplate = new RestTemplate();
//        String fileName = teamFilesTree.getRealName();
//        String extension = teamFilesTree.getSuffix();
//        if (!trainUrl.getConfigValue().equals("") && trainUrl.getConfigValue() != null) {
//            String url = UriComponentsBuilder.fromHttpUrl(trainUrl.getConfigValue() + "/backend/v1/upload/file-name-check")
//                    .queryParam("extension", extension)
//                    .queryParam("fileName", fileName).toUriString();
//            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
//            String body = exchange.getBody();
//            JSONObject jsonObject = JSONUtil.parseObj(body);
//            Boolean dataValue = jsonObject.getBool("data");
//            if (dataValue.equals(true)) {
//                throw new BadRequestException("培训系统已经存在相同文件名的资源，请修改文件名后重新加入培训！");
////                return R.fail()(ResultEnum.PERM_ERROR.getNum(), "培训系统已经存在相同文件名的资源，请修改文件名后重新加入培训！");
//            }
//        } else {
//            throw new BadRequestException("培训配置错误！");
////            return R.fail()(ResultEnum.PERM_ERROR.getNum(), "培训配置错误！");
//        }
//
//        MessageDto messageDto = new MessageDto();
//        messageDto.setType("team");
//        messageDto.setUserId(user.getId());
//        messageDto.setUserName(user.getUsername());
//        messageDto.setTreeNodeId(teamFilesTree.getId());
//        Team team = teamService.getById(teamFilesTree.getTeamId());
//
//        String suffix = teamFilesTree.getSuffix();
//        if (suffix == null) {
//            return R.fail()(ResultEnum.PERM_ERROR.getNum(), "该类型文件无法加入TMS资源");
//
//        }
//        String path = FileUtil.tmsFileCheck(suffix);
//        if (path == null){
//            return R.fail()(ResultEnum.PERM_ERROR.getNum(), "该类型文件无法加入TMS资源");
//        }
//        //记录加入TMS资源的文档
//        teamFilesTree.setToTms("true");
//        teamFilesTreeService.updateById(teamFilesTree);
//
//        //copy到TMS文档资源桶里
//        Storage copy = fileStorageUtils.copy(user.getId().toString(), user.getUsername(), FileEnums.TMS_FILE, StorageFolderTypeEnum.TMS_BUCKET.getCode(), teamFilesTree.getStorageId(), null, null, path);
//
//        Map<String, Object> map = new HashMap<>();
//        map.put("team", team);
//        map.put("type", "add");
//        map.put("fileTree", teamFilesTree);
//        map.put("storage", copy);
//        messageDto.setDataJson(map);
//        rabbitMessageSender.sendFileEcm2Tms(messageDto);
//        System.out.println(teamFilesTree);
//        return R.ok()();
//    }

//    @Log("团队文档取消培训资源")
//    @ApiOperation("团队文档取消培训资源")
//    @GetMapping(value = "/cancelTMS")
//    @ResponseBody
//    public R cancelTMS(String id) {
//        TeamFilesTree teamFilesTree = teamFilesTreeService.getById(id);
//        LoginUser user = LoginHelper.getLoginUser();
//
//        //判断是否有权限
//        if (!teamRelevanceRoleService.checkPermission(id, teamFilesTree.getTeamId(), user, TeamParamEnum.JURISDICTION.getParam())) {
//            return R.fail(ResultEnum.PERM_ERROR.getNum(), "无操作权限，请联系管理员");
//        }
//
//        //判断是否开启TMS继承
//        SysParametersConfigDto trainEnable = sysConfigUtils.getByConfigCodeAfter("train_enable", SysParametersConfigEnums.SYS_EXTERNAL_CONFIG);
//        if (!trainEnable.getConfigValue().equals("true")) {
//            return R.fail(ResultEnum.PERM_ERROR.getNum(), "未开启TMS集成");
//        }
//
//        //记录加入TMS资源的文档
//        teamFilesTree.setToTms("false");
//        teamFilesTreeService.updateById(teamFilesTree);
//
//        MessageDto messageDto = new MessageDto();
//        messageDto.setType("team");
//        messageDto.setUserId(user.getId());
//        messageDto.setUserName(user.getUsername());
//        messageDto.setTreeNodeId(teamFilesTree.getId());
//        Map<String, Object> map = new HashMap<>();
//        map.put("type", "delete");
//        map.put("fileTree", teamFilesTree);
//        messageDto.setDataJson(map);
//        rabbitMessageSender.sendFileEcm2Tms(messageDto);
//        System.out.println(teamFilesTree);
//
//
//        return R.ok();
//    }

//    @Log("创建项目模板")
//    @ApiOperation("创建项目模板")
    @GetMapping(value = "/createFolderTemplate")
    public R createFolderTemplate(Long template, Long parentFolderId, String folderName) {
        return R.ok(teamFilesTreeService.createTemplate(template, parentFolderId, folderName, LoginHelper.getLoginUser()));
    }

//    @Log("提交企业库")
//    @ApiOperation("提交企业库")
    @GetMapping(value = "/commitEnterprise")

    public R commitEnterprise(String id,String enterpriseId) {

        TeamToEnterpriseDto teamToEnterprise = teamFilesTreeService.assembleTeamToEnterprise(id);
        LoginUser user = LoginHelper.getLoginUser();

        if (teamToEnterprise == null){
            return R.fail(ResultEnum.PERM_ERROR.getNum(), "无操作权限，请联系管理员");
        }

        //上传至企业库
        enterpriseFilesTreeService.createFolder(teamToEnterprise, String.valueOf(user.getUserId()),null,user.getUsername(),enterpriseId,1);
        return R.ok();


    }



//    @Log("获取节点信息")
//    @ApiOperation("获取节点信息")
    @GetMapping(value = "/getInfoByTreeId")
    public R getInfoByTreeId(String id) {
        return R.ok(teamFilesTreeService.getById(id));
    }

    /**
     * 新增置顶
     *
     * @param top
     * @return
     */
    @PostMapping(value = "/top")
//    @ApiModelProperty("新增置顶")
    public R insertTopMark(@RequestBody FilesTreeTop top) {
        return teamFilesTreeService.topMark(top);
    }

}
